
<template>
  <div class="risk-content start-exam">
    <div class="exam-title">
      <div class="un-exam">{{ data.ExamName }}</div>
    </div>
    <div class="exam-content">
      <!-- 一 -->
      <div v-for="(val, key) in list" :key="key">
        <div class="mb-10 questions-title">
          <span v-if="key == 0">一、</span>
          <span v-if="key == 1">二、</span>
          <span v-if="key == 2">三、</span>
          <span v-if="key == 3">四、</span>
          <span v-if="key == 4">五、</span>
          {{ val.QName }}共{{ val.children.length }}题（{{
            val.Score + ".0"
          }}分）
        </div>

        <div
          class="mb-10 exam-questions"
          v-for="(item, index) in val.children"
          :key="index"
        >
          <div class="mb-10">
            {{ item.SEQ + 1 }}、{{ item.QName }}（{{ item.Score + ".0分" }}）
          </div>
          <div v-if="item.QType == 1">
            <van-radio-group v-model="item.ItemName">
              <van-radio
                :name="v.ItemName"
                class="mb-10"
                checked-color="#3CB371"
                v-for="(v, i) in item.Items"
                :key="i"
                >{{ v.ItemName }}.{{ v.Item }}</van-radio
              >
            </van-radio-group>
          </div>
          <div v-if="item.QType == 2">
            <van-checkbox-group v-model="item.ItemName">
              <van-checkbox
                :name="v2.ItemName"
                class="mb-10"
                checked-color="#3CB371"
                v-for="(v2, i2) in item.Items"
                :key="i2"
                >{{ v2.ItemName }}.{{ v2.Item }}</van-checkbox
              >
            </van-checkbox-group>
          </div>
          <div v-if="item.QType == 3">
            <van-radio-group v-model="item.ItemName">
              <van-radio
                :name="v.ItemName"
                class="mb-10"
                checked-color="#3CB371"
                v-for="(v, i) in item.Items"
                :key="i"
                >{{
                  v.ItemName == "A" ? "正确" : v.ItemName == "B" ? "错误" : ""
                }}</van-radio
              >
            </van-radio-group>
          </div>
          <div v-if="item.QType == 4">
            <van-field
              v-model="v.ItemName"
              v-for="(v, i) in item.Items"
              :key="i"
              label-width="40"
              class="input_text"
              :label="i + 1 + '、'"
              placeholder="请输入答案"
              border
            />
          </div>
          <div v-if="item.QType == 5">
            <van-field
              v-model="item.ItemName"
              label="答案"
              label-width="40"
              rows="3"
              type="textarea"
              placeholder="请输入答案"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="exam-btns">
      <div class="exam-btns-l">
        <div class="mb-5">参加考试人：{{ chnName }}</div>
        <div v-if="data.ExamMins">剩余时间：{{ text }}</div>
      </div>
      <van-button type="info" @click="_submit()">提交</van-button>
    </div>
  </div>
</template>

<script>
import { getExamPaperQuestionDetail, finishExam } from "@/api/ExExam";
import formatSeconds from "@/utils/formatSeconds.js";
import { mapGetters } from "vuex";
import store from "@/store/index";
import { is_weixin } from "@/utils/common.js";
export default {
  data() {
    return {
      id: this.$route.query.id,
      loading: false,
      data: {},
      text: "",
      list: [],
    };
  },
  computed: {
    ...mapGetters(["chnName"]),
  },
  created() {
    this.getDetail();
  },
  mounted() {
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
  },
  methods: {
    goBack() {
      this.$dialog
        .confirm({
          title: "询问",
          message: `您正在考试中，确定要退出吗？`,
        })
        .then(() => {
          // this.$router.replace({ path: '/Train/ExExamExplain?id=' + this.id })
          this.$router.go(-1);
        })
        .catch(() => {
          // on cancel
        });
    },
    getDetail() {
      this.loading = true;
      getExamPaperQuestionDetail({ id: this.id }).then((res) => {
        this.loading = false;
        res.data.Questions.forEach((item, index) => {
          item.SEQ = index;
        });
        res.data.Questions.push(
          {
            parentQType: 1,
            QName: "单选题",
            QType: 0,
            Score: 0,
          },
          {
            parentQType: 2,
            QName: "多选题",
            QType: 0,
            Score: 0,
          },
          {
            parentQType: 3,
            QName: "判断题",
            QType: 0,
            Score: 0,
          },
          {
            parentQType: 4,
            QName: "填空题",
            QType: 0,
            Score: 0,
          },
          {
            parentQType: 5,
            QName: "简答题",
            QType: 0,
            Score: 0,
          }
        );
        let arryList = this.toTree(res.data.Questions);
        let newArr = arryList.filter(
          (item, index) => item.children != undefined
        );

        // 计算总分
        newArr.forEach((item) => {
          if (item.children) {
            item.children.forEach((item1) => {
              item.Score += item1.Score;
            });
          }
        });

        res.data.ExamMins = parseInt(res.data.ExamMins * 60);
        this.list = newArr;
        this.data = res.data;
        this.time();
      });
    },
    toTree(data) {
      var result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach((item) => {
        delete item.children;
      });
      let map = {};
      data.forEach((item) => {
        map[item.parentQType] = item;
      });

      data.forEach((item) => {
        let parent = map[item.QType];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    // 提交考试
    _submit() {
      const _this = this;
      const newList = this.list.filter((item) => item.children);
      var Details = [];
      var IsExamSign = false;
      newList.filter((item) => {
        item.children.filter((item1) => {
          if (item1.QType == 4) {
            IsExamSign = true;
            let ItemName = [];
            item1.Items.map((v) => {
              if (v.ItemName) {
                ItemName.push(v.ItemName);
              }
            });
            Details.push({
              Answer: Array.isArray(ItemName) ? ItemName.join(",") : ItemName,
              QCode: item1.QCode,
            });
          } else {
            Details.push({
              Answer: Array.isArray(item1.ItemName)
                ? item1.ItemName.join(",")
                : item1.ItemName,
              QCode: item1.QCode,
            });
          }
        });
      });
      const data = {
        Details: Details,
        ID: this.data.ID,
        SubjectID: "",
      };
      if (data.Details.every((item) => item.Answer)) {
        this.$dialog
          .confirm({
            title: "询问",
            message: `您确定要提交本次考试吗？`,
          })
          .then(() => {
            finishExam(data).then((res) => {
              // if (IsExamSign) {
              // 	_this.$router.push('/Train/ExamSign?id=' + data.ID)
              // } else {
              // 	_this.$router.push('/Train/ExamResult?id=' + data.ID)
              // }
              // _this.$router.push('/Train/ExamResult?id=' + data.ID)
              localStorage.setItem("examResultID", _this.data.ID);
              if (window.jsListener || window.webkit) {
                if (window.jsListener) {
                  window.jsListener.doBackNum(2);
                }

                
                if (is_weixin) {
                  //如果是微信执行的操作
                  _this.$router.go(-3);
                } else {
                  //如果不是微信执行的操作
                  if (window.webkit.messageHandlers) {
                    window.webkit.messageHandlers.doBack.postMessage(2);
                  }
                }
              } else {
                _this.$router.go(-3);
              }
            });
          });
      } else {
        this.$dialog
          .confirm({
            title: "询问",
            message: `您还有未做的题目，确认是否提交？`,
          })
          .then(() => {
            finishExam(data).then((res) => {
              // if (IsExamSign) {
              // 	_this.$router.push('/Train/ExamSign?id=' + data.ID)
              // } else {
              // 	_this.$router.push('/Train/ExamResult?id=' + data.ID)
              // }
              // _this.$router.push('/Train/ExamResult?id=' + data.ID)
              localStorage.setItem("examResultID", _this.data.ID);
              if (window.jsListener || window.webkit) {
                if (window.jsListener) {
                  window.jsListener.doBackNum(2);
                }

                if (is_weixin) {
                  //如果是微信执行的操作
                  _this.$router.go(-3);
                } else {
                  //如果不是微信执行的操作
                  if (window.webkit.messageHandlers) {
                    window.webkit.messageHandlers.doBack.postMessage(2);
                  }
                }

                // if (window.webkit.messageHandlers) {
                //   window.webkit.messageHandlers.doBack.postMessage(2);
                // }
              } else {
                _this.$router.go(-3);
              }
            });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    _goExam() {
      this.$router.push("/Train/ExExamExplain?id=" + item.ID);
    },
    // 倒计时提交
    _submitTime() {
      const _this = this;
      const newList = this.list.filter((item) => item.children);
      var Details = [];
      var IsExamSign = false;
      newList.filter((item) => {
        item.children.filter((item1) => {
          if (item1.QType == 4) {
            IsExamSign = true;
            let ItemName = [];
            item1.Items.map((v) => {
              if (v.ItemName) {
                ItemName.push(v.ItemName);
              }
            });
            Details.push({
              Answer: Array.isArray(ItemName) ? ItemName.join(",") : ItemName,
              QCode: item1.QCode,
            });
          } else {
            Details.push({
              Answer: Array.isArray(item1.ItemName)
                ? item1.ItemName.join(",")
                : item1.ItemName,
              QCode: item1.QCode,
            });
          }
        });
      });
      const data = {
        Details: Details,
        ID: this.data.ID,
        SubjectID: "",
      };
      finishExam(data).then((res) => {
        // if (IsExamSign) {
        // 	_this.$router.push('/Train/ExamSign?id=' + data.ID)
        // } else {
        // 	_this.$router.push('/Train/ExamResult?id=' + data.ID)
        // }
        // _this.$router.push('/Train/ExamResult?id=' + data.ID)
        store.commit("updateResultID", _this.data.ID);
        _this.$router.go(-3);
      });
    },
    // 倒计时
    time() {
      var that = this;
      if (that.data.ExamMins == 0) {
        that.text = "";
      } else {
        that.text = formatSeconds(that.data.ExamMins);
        that.data.ExamMins--;
        setTimeout(function () {
          // console.log(that.data.ExamMins,'that.data.ExamMins');
          // 时间小于1s时，提交
          if (that.data.ExamMins < 1) {
            that._submitTime();
          }
          that.time();
        }, 1000);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.risk-content {
  background-color: #fff;
  min-height: 100vh;
}
.questions-title {
  background-color: #e8f1f8;
  padding: 10px;
}
.exam-title {
  height: 30px;
  background-color: #e8f1f8;
  line-height: 30px;
  padding: 0 10px;
  font-size: 14px;
  .un-exam {
    display: inline-block;
    height: 100%;
    border-bottom: 2px solid #333;
  }
}
.exam-content {
  height: calc(100vh - 60px);
  overflow: hidden;
  overflow-y: auto;
  font-size: 14px;
}
.exam-content::-webkit-scrollbar {
  display: none;
}
.exam-questions {
  padding: 10px;
  border-bottom: 1px solid #eee;
  > div {
    line-height: 1.3;
    font-size: 12px;
  }
}
.exam-btns {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  font-size: 14px;
  background-color: #fff;
  border-top: 1px solid #ccc;
  .exam-btns-l {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 50px;
    padding-left: 10px;
    font-size: 12px;
  }
  .van-button {
    width: 25%;
    height: 50px;
    border-radius: 0;
  }
}
</style>
<style lang="less">
.start-exam {
  .van-field__control {
    background-color: #f8f8f8 !important;
  }
}
</style>